package cn.thrjit.listener;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.ObjectUtil;
import cn.thrjit.pojo.domain.Login;
import cn.thrjit.rocketmq.Constants;
import cn.thrjit.service.ILoginService;
import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;


/**
 * 初始化管理员账号的监听器
 */
@Component
public class AdminInitListener implements ApplicationListener<ApplicationReadyEvent> {
    @Autowired
    private ILoginService loginService;
    /**
     * 当容器刷新时会执行此方法
     * @param event
     */
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        Login login = loginService.getOne(new LambdaQueryWrapper<Login>()
                .eq(Login::getUsername, "admin")// 判断用户名是否为admin
                .eq(Login::getType, Constants.Login.TYPE_ADMIN)// 判断类型是否为0（管理员）
                .eq(Login::getAdmin, true));// 判断状态是否为true（正常）
        if(ObjectUtil.isNull(login)){
            login = new Login();
            login.setId(0L);
            String hashpw = BCrypt.hashpw("123456", BCrypt.gensalt());
            login.setUsername("admin");
            login.setPassword(hashpw);
            login.setType(Constants.Login.TYPE_ADMIN);
            login.setEnabled(true);
            login.setAvatar(Constants.DEFAULT_AVATAR);
            login.setAdmin(true);
            login.setNickName("admin");
            login.setName("admin");
            login.setCreateTime(new Date());
            login.setDeleted(false);
            login.setVersion(0);
            loginService.save(login);
            System.out.println("初始化管理员账号成功！");
        }

    }
}
